package com.cyl.manager.aws.service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.manager.aws.domain.entity.SystemStatistics;
import com.cyl.manager.aws.domain.query.SystemStatisticsQuery;
import com.cyl.manager.aws.mapper.SystemStatisticsMapper;
import com.cyl.manager.oms.domain.entity.Aftersale;
import com.cyl.manager.oms.mapper.AftersaleMapper;
import com.cyl.manager.oms.mapper.OrderItemMapper;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.entity.Member;
import com.cyl.manager.ums.mapper.MemberCartMapper;
import com.cyl.manager.ums.mapper.MemberLogininforMapper;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import cn.hutool.core.collection.CollectionUtil;

/**
 * 系统数据统计Service业务层处理
 *
 * @author zcc
 */
@Service
public class SystemStatisticsService {
    @Autowired
    private SystemStatisticsMapper systemStatisticsMapper;

    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private AftersaleMapper aftersaleMapper;

    @Autowired
    private MemberLogininforMapper memberLogininforMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private MemberCartMapper memberCartMapper;

    /**
     * 查询系统数据统计
     *
     * @param id 系统数据统计主键
     * @return 系统数据统计
     */
    public SystemStatistics selectById(Long id) {
        return systemStatisticsMapper.selectById(id);
    }
    
 
    /**
     * 查询系统数据统计列表
     *
     * @param query 查询条件
     * @param page  分页条件
     * @return 系统数据统计
     */
    public PageImpl<SystemStatistics> selectList(SystemStatisticsQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        Long deptZbjId = query.getDeptZbjId();
    	Long deptTzId = query.getDeptTzId();
    	Long deptDpId = query.getDeptDpId();
        String type = query.getType();
        
        String date = "date , ";
        String sfDate =  query.getSfDate();
        if(sfDate!=null && "false".equals(sfDate)) {
        	date = "";
        }
        String selectGroupBy = "date";
        if("0".equals(type)) {
        	selectGroupBy = ("date");
        }
        if("1".equals(type)) {
        	selectGroupBy = (date + " dept_zbj_id ");
        }
        if("2".equals(type)) {
        	selectGroupBy = (date +  " dept_zbj_id ,dept_tz_id ");
        }
        if("3".equals(type)) {
        	selectGroupBy = (date +  " dept_zbj_id , dept_tz_id , dept_dp_id ");
        }
       QueryWrapper<SystemStatistics> queryWrapper = new QueryWrapper<>();
	   queryWrapper.select(selectGroupBy + "	,\r\n" + 
	   		"	sum(login_member_count) as login_member_count,\r\n" + 
	   		"	sum(register_member_count) as register_member_count,\r\n" + 
	   		"	sum(add_cart_member_count) as add_cart_member_count,\r\n" + 
	   		"	sum(create_order_member_count) as create_order_member_count,\r\n" + 
	   		"	sum(deal_member_count) as deal_member_count,\r\n" + 
	   		"	sum(order_count) as order_count,\r\n" + 
	   		"	sum(deal_count) as deal_count,\r\n" + 
	   		"	sum(deal_amount) as deal_amount,\r\n" + 
	   		"	sum(aftersale_count) as aftersale_count,\r\n" + 
	   		"	sum(aftersale_amount) as aftersale_amount,\r\n" + 
	   		"	max(sum_member_count) as sum_member_count,\r\n" + 
	   		"	sum(create_order_product_count) as create_order_product_count ");

        if (query.getBeginTime() != null && query.getEndTime() != null){
        	queryWrapper.ge("date", query.getBeginTime());
        	queryWrapper.lt("date", query.getEndTime());
        }
        if(deptZbjId!=null) {
        	queryWrapper.eq("dept_zbj_id", deptZbjId);
        }
		if(deptTzId!=null) {
			queryWrapper.eq("dept_tz_id", deptTzId);     	
		}
		if(deptDpId!=null) {
			queryWrapper.eq("dept_dp_id", deptDpId);
		}
		queryWrapper.groupBy(selectGroupBy);
 
        List<SystemStatistics> statList = systemStatisticsMapper.selectList(queryWrapper);
        long total = statList.size();
        if(page!=null) {
             total = ((Page)statList).getTotal();
        }
//        if ((query.getBeginTime() == null && query.getEndTime() == null) || (query.getEndTime() != null && query.getEndTime().isAfter(LocalDateTime.now()))){
//            SystemStatistics stat = this.stat(deptZbjId, deptTzId, deptDpId,LocalDateTime.of(LocalDate.now(), LocalTime.MIN), LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
//            statList.add(0, stat);
//            return new PageImpl<>(statList, page, total);
//        }
       if(page==null) {
           return new PageImpl<>(statList);
       }else {
           return new PageImpl<>(statList, page, total);
       }
       
    }

    /**
     * 新增系统数据统计
     *
     * @param systemStatistics 系统数据统计
     * @return 结果
     */
    public int insert(SystemStatistics systemStatistics) {
        return systemStatisticsMapper.insert(systemStatistics);
    }

    /**
     * 修改系统数据统计
     *
     * @param systemStatistics 系统数据统计
     * @return 结果
     */
    public int update(SystemStatistics systemStatistics) {
        return systemStatisticsMapper.updateById(systemStatistics);
    }

    /**
     * 删除系统数据统计信息
     *
     * @param id 系统数据统计主键
     * @return 结果
     */
    public int deleteById(Long id) {
        return systemStatisticsMapper.deleteById(id);
    }


    
    public SystemStatistics stat(Long deptZbjId,Long deptTzId,Long deptDpId,LocalDateTime startTime, LocalDateTime endTime) {
        //统计下单用户数、成交用户数、下单数、成交数、成交金额
        SystemStatistics systemStatistics = orderMapper.statNewAndDeal(startTime, endTime, deptZbjId, deptTzId, deptDpId);
        //统计成交用户数
        systemStatistics.setDealMemberCount(orderMapper.statDealMember(startTime, endTime, deptZbjId, deptTzId, deptDpId));
        //统计售后
        LambdaQueryWrapper<Aftersale> wrapper = new LambdaQueryWrapper<>();
        if(deptZbjId!=null) {
			wrapper.eq(Aftersale::getDeptZbjId, deptZbjId);     	
		}
        if(deptTzId!=null) {
            wrapper.eq(Aftersale::getDeptTzId, deptTzId);
        }
		if(deptDpId!=null) {
			wrapper.eq(Aftersale::getDeptDpId, deptDpId);
		}
        wrapper.between(Aftersale::getCreateTime, startTime, endTime);
        wrapper.orderByDesc(Aftersale::getCreateTime);
        List<Aftersale> aftersaleList = aftersaleMapper.selectList(wrapper);
        if (CollectionUtil.isEmpty(aftersaleList)) {
            systemStatistics.setAftersaleCount(0);
            systemStatistics.setAftersaleAmount(BigDecimal.ZERO);
        } else {
            Map<Long, BigDecimal> map = aftersaleList.stream().collect(Collectors.toMap(Aftersale::getOrderId, Aftersale::getReturnAmount, (v1, v2) -> v1, LinkedHashMap::new));
            systemStatistics.setAftersaleCount(map.values().size());
            systemStatistics.setAftersaleAmount(map.values().stream().reduce(BigDecimal::add).get());
        }
        //统计登录用户数
        systemStatistics.setLoginMemberCount(memberLogininforMapper.statLoginMember(startTime, endTime, deptZbjId, deptTzId, deptDpId));
        //统计注册用户
        LambdaQueryWrapper<Member> memberWrapper = new LambdaQueryWrapper<>();
    
		if(deptZbjId!=null) {
			memberWrapper.eq(Member::getDeptZbjId, deptZbjId);     	
		}
	    if(deptTzId!=null) {
        	memberWrapper.eq(Member::getDeptTzId, deptTzId);
        }
		if(deptDpId!=null) {
			memberWrapper.eq(Member::getDeptDpId, deptDpId);
		}
        memberWrapper.between(Member::getCreateTime, startTime, endTime);
        systemStatistics.setRegisterMemberCount(memberMapper.selectCount(memberWrapper));
        //统计加购数
        systemStatistics.setAddCartMemberCount(memberCartMapper.statAddCount(startTime, endTime, deptZbjId, deptTzId, deptDpId));
        
        //用户总数
        LambdaQueryWrapper<Member> memberCountWrapper = new LambdaQueryWrapper<>();
       
    	if(deptZbjId!=null) {
    		memberCountWrapper.eq(Member::getDeptZbjId, deptZbjId);     	
		}
        if(deptTzId!=null) {
        	memberCountWrapper.eq(Member::getDeptTzId, deptTzId);
        }
		if(deptDpId!=null) {
			memberCountWrapper.eq(Member::getDeptDpId, deptDpId);     	
		}

        systemStatistics.setSumMemberCount(memberMapper.selectCount(memberCountWrapper));
   
        //商品数量
        systemStatistics.setCreateOrderProductCount(orderItemMapper.getOrderProductSum(startTime, endTime, deptZbjId, deptTzId, deptDpId));
        

		systemStatistics.setDeptZbjId(deptZbjId);
		systemStatistics.setDeptTzId(deptTzId);
		systemStatistics.setDeptDpId(deptDpId);
        systemStatistics.setDate(startTime);
        return systemStatistics;
    }
    
    
   
}
